package com.app.car.other;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;

import com.app.car.R;
import com.app.car.basis.BasisActivity;
import com.app.car.basis.BasisApp;
import com.app.car.login.LoginActivity;
import com.flyco.dialog.listener.OnBtnClickL;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import my.DialogUtils;
import my.LogUtil;
import my.http.MyHttpUtils;


public class WebViewX5Activity extends BasisActivity  {

    WebView mWebView;
    String wapurl;
    String title;
    boolean isHeader = true;

    public static void toWebView(BasisActivity context, String url, String title) {

        if(TextUtils.isEmpty(url))return;


        Intent intent = new Intent(context, WebViewX5Activity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        LogUtil.i("url---->" + url);
        context.startActivity(intent);
    }

    public static void toWebView(BasisActivity context, String url, String title,String filename) {

        if(TextUtils.isEmpty(url))return;


        Intent intent = new Intent(context, WebViewX5Activity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        LogUtil.i("url---->" + url);
        context.startActivity(intent);
    }

    public static void toWebViewWeixin(Context context, String url, String title) {
        Intent intent = new Intent(context, WebViewX5Activity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("weixin", true);
        LogUtil.i("url---->" + url);
        context.startActivity(intent);
    }

    public static void toWebViewPaddingTop(Context context, String url, String title) {
        Intent intent = new Intent(context, WebViewX5Activity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("top", true);
        LogUtil.i("url---->" + url);
        context.startActivity(intent);
    }

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        setContentView(R.layout.base_webview_local_x5);
        super.initViews();

        setTitle("");
        setTitleLeftButton(new OnClickListener() {
            @Override
            public void onClick(View v) {
                    finish();

            }
        });

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
         mWebView.getSettings().setSupportZoom(true);//设定支持缩放
         mWebView.getSettings().setBuiltInZoomControls(true);
//        mWebView.setInitialScale(20);
        mWebView.getSettings().setUseWideViewPort(true);  ////设定支持viewport
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setSavePassword(false);
//         mWebView.getSettings().setAppCachePath("external/chromium/net/disk_cache/");
        // mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setSaveEnabled(true);
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);

        //启用数据库
        mWebView.getSettings().setDatabaseEnabled(true);
//设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        mWebView.getSettings().setGeolocationDatabasePath(dir);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        //解除数据阻止
        mWebView.getSettings().setBlockNetworkImage(false);
        // setZoomControlGone(mWebView);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.clearCache(true);
//		webSet.setRenderPriority(WebSettings.RenderPriority.HIGH);
        //
        mWebView.setWebViewClient(new MyWebViewClient());
//        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebChromeClient(chromeClient);
        mWebView.requestFocus();

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);

//        Acp.getInstance(this).request(new AcpOptions.Builder()
//                        .setPermissions(Manifest.permission.INTERNET
//                                , Manifest.permission.ACCESS_COARSE_LOCATION
//                                , Manifest.permission.ACCESS_FINE_LOCATION
//                        ).build(),
//                new AcpListener() {
//                    @Override
//                    public void onGranted() {
//                        initUrl();
//                    }
//
//                    @Override
//                    public void onDenied(List<String> permissions) {
//                        BasisApp.showToast(permissions.toString() + "权限拒绝");
////                        DialogUtils.DialogOKmsgFinish(mContext, "拒绝权限，结束程序");
//                    }
//                });
        initUrl();
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (mWebView != null) {
            try {
                mWebView.setWebViewClient(null);
                mWebView.destroy();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initUrl() {
        wapurl = getIntent().getStringExtra("url");
         title = getIntent().getStringExtra("title");
        if (wapurl == null || wapurl.equals("")) {
            BasisApp.showToast("网页地址不存在");
        }

        if (!TextUtils.isEmpty(title)) {
            setTitle(title);
        } else {
            setTitle("");
        }
        mWebView.addJavascriptInterface(new WebViewX5Activity.MyJavaScriptObject(),"jsbrige");
        // myProgressDialog.show();
        if(isHeader){
//            Map<String, String > map = MyHttpUtils.getWebviewHeader();
//            mWebView.loadUrl(wapurl,map);
            mWebView.loadUrl(wapurl, MyHttpUtils.getWebViewHeader());
//            mWebView.loadUrl(wapurl);
        }else {
            mWebView.loadUrl(wapurl);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (mWebView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            mWebView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private Handler mHandler = new Handler();

    @SuppressLint("NewApi")
    class MyWebViewClient extends WebViewClient {
        String loginCookie;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            // if(myProgressDialog != null &&
            // !myProgressDialog.isShowing())myProgressDialog.show();
            LogUtil.i("shouldOverrideUrlLoading---url-->"+url);
            if (url.startsWith("mailto:") || url.startsWith("geo:")
                    || url.startsWith("tel:") || url.indexOf(".3gp") != -1 || url.indexOf(".mp4") != -1
                    || url.indexOf(".flv") != -1
                    || url.indexOf(".swf") != -1) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }else {
//                mWebView.loadUrl(url);
                mWebView.loadUrl(url, MyHttpUtils.getWebViewHeader());
            }
            return true;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            // TODO Auto-generated method stub
            // CookieManager cookieManager = CookieManager.getInstance();
            // loginCookie = cookieManager.getCookie(url);
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            // CookieManager cookieManager = CookieManager.getInstance();
            // cookieManager.setCookie(url, loginCookie);
            super.onPageFinished(view, url);
            dismissProgress();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
            if (!WebViewX5Activity.this.isFinishing()) {
                showProgress();
            }
        }


    }

    private WebChromeClient chromeClient = new WebChromeClient() {

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissionsCallback callback) {
            LogUtil.i("onGeolocationPermissionsShowPrompt--->");
//            super.onGeolocationPermissionsShowPrompt(s, geolocationPermissionsCallback);
//            geolocationPermissionsCallback.invoke(s, true, false);
            final boolean remember = true;
            DialogUtils.DialogTwo(mContext, "", origin + "允许获取您的地理位置信息吗？", "允许", "不允许", new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    callback.invoke(origin, true, remember);
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    callback.invoke(origin, false, remember);
                }
            });
        }

        @Override
        public boolean onJsConfirm(WebView arg0, String arg1, String arg2, JsResult arg3) {
            return super.onJsConfirm(arg0, arg1, arg2, arg3);
        }

        View myVideoView;
        View myNormalView;
        IX5WebChromeClient.CustomViewCallback callback;

        ///////////////////////////////////////////////////////////
        //  `

        /**
         * 全屏播放配置
         */
        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
            View normalView =  WebViewX5Activity.this.findViewById(R.id.webview);
            ViewGroup viewGroup = (ViewGroup) normalView.getParent();
            viewGroup.removeView(normalView);
            viewGroup.addView(view);
            myVideoView = view;
            myNormalView = normalView;
            callback = customViewCallback;
        }

        @Override
        public void onHideCustomView() {
            if (callback != null) {
                callback.onCustomViewHidden();
                callback = null;
            }
            if (myVideoView != null) {
                ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
                viewGroup.removeView(myVideoView);
                viewGroup.addView(myNormalView);
            }
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            WebViewX5Activity.this.uploadFile = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            (WebViewX5Activity.this).startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER);
        }

        public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
            WebViewX5Activity.this.uploadFile = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            (WebViewX5Activity.this).startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER);
        }

        @Override
        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String captureType) {
            LogUtil.i("openFileChooser--->");
            WebViewX5Activity.this.uploadFile = uploadFile;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            (WebViewX5Activity.this).startActivityForResult(Intent.createChooser(i, "选择文件"),
                    FILE_CHOOSER);
            super.openFileChooser(uploadFile, acceptType, captureType);
        }

        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            LogUtil.i("openFileChooser--5.0->");
            WebViewX5Activity.this.mUploadCallbackAboveL = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            WebViewX5Activity.this.startActivityForResult(
                    Intent.createChooser(i, "选择文件"),
                    FILE_CHOOSER);
            return true;
        }

        @Override
        public void onReceivedTitle(WebView arg0, final String arg1) {
            super.onReceivedTitle(arg0, arg1);
//            Log.i("yuanhaizhou", "webpage title is " + arg1);
            if (TextUtils.isEmpty(title)) {
                setTitle(arg1);
            }

        }
    };

    private ValueCallback<Uri> uploadFile;
    ValueCallback<Uri[]> mUploadCallbackAboveL;
    private static final int FILE_CHOOSER = 22;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != FILE_CHOOSER
        ) {
            return;
        }
        LogUtil.i("onActivityResult--onActivityResult->" + resultCode);
        if (resultCode == RESULT_OK) {

            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
                return;
            }

            if (null != uploadFile) {
                Uri result = data == null || resultCode != RESULT_OK ? null
                        : data.getData();
                uploadFile.onReceiveValue(result);
                uploadFile = null;
            }
        } else {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }

        }

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILE_CHOOSER
                || mUploadCallbackAboveL == null) {
            return;
        }
        LogUtil.i("onActivityResultAboveL-------->"+resultCode);
        Uri[] results =  null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }


    @SuppressWarnings("javadoc")
    public class MyJavaScriptObject {

        //sdk17版本以上加上注解
        public MyJavaScriptObject() {
        }

        @JavascriptInterface
        public void onFinishWebview() {
            finish();
        }
        @JavascriptInterface
        public void onTokenPast(){
            LoginActivity.toLoginAllClear(mContext);
        }
        @JavascriptInterface
        public String getToken(){
//            return "bearer "+LoginBean.getUserToken();
            return "";
        }
        @JavascriptInterface
        public String getTestString(){
            return "TEST！";
        }
        @JavascriptInterface
        public void showToast(String name) {
            WebViewX5Activity.this.showToast(name);
        }
        @JavascriptInterface
        public void downLoadAndOpen(String url) {
        
        }


    }

    public void writeData(){
        String key = "ff-zdpa-wx-token";
//        String value = LoginBean.getUserToken();
        String value = "LoginBean.getUserToken()";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript("window.localStorage.setItem('"+ key +"','"+ value +"');", null);
//            mWebView.evaluateJavascript("window.localStorage.setItem('"+ key2 +"','"+ val2 +"');", null);
        } else {
            mWebView.loadUrl("javascript:localStorage.setItem('"+ key +"','"+ value +"');");
        }
    }

    @Subscribe
    public void onWebEvent(EventWeb event){
        if(isFinishing())return;
        if(event.type == EVENT_TYPE_MSGCODE){
            mWebView.loadUrl("javascript:localStorage.setItem('"+ event.getMsgCode() +"');");
        }
    }

    public static final int EVENT_TYPE_MSGCODE = 31;
    public static class EventWeb{

        int type;
        private String msgCode;

        public EventWeb(int type) {
            this.type = type;
        }
        public EventWeb(String msgCode) {
            this.type = EVENT_TYPE_MSGCODE;
            this.msgCode = msgCode;
        }

        public String getMsgCode() {
            return msgCode;
        }

        public void setMsgCode(String msgCode) {
            this.msgCode = msgCode;
        }
    }



//    @Override
//    public void onGeolocationPermissionsShowPrompt(String origin,Callback callback){
//        callback.invoke(origin, true, false);  
//        super.onGeolocationPermissionsShowPrompt(origin, callback);
//
//    }
}
